package com.banciyuan.bcywebview.biz.main.mineinfo.mywork;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpaceApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.banciyuan.bcywebview.utils.http.BcyPair;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.daoexample.model.NativeWriteWork;
import de.greenrobot.daoexample.model.Novel;
import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.WorkMonth;
import de.greenrobot.daoexample.model.WorkYear;

/**
 * Created by hy on 2016/3/23.
 */
public class WriteWorkActivity extends BaseActivity {
    private RequestQueue mQueue;
    private ProgressbarHelper mProgressbarHelper;
    private ListView mListView;
    private TextView tvMainworkTotalCount;
    private String wp_id;
    private String totalCount;

    private boolean mLastItemVisible = false;
    private boolean loading = false;
    private boolean end_flag = false;
    private int page = 1;

    private boolean work_flag = false;
    private boolean year_flag = false;

    private Map<String, WorkYear> workYearMap = new HashMap<>();
    private List<Novel> tempList;
    private MyNovelAdapter myNovelAdapter;
    private List<NativeWriteWork> nativeWriteWorkList = new ArrayList<>();
    private Set<String> existedWorkMonth = new HashSet<>();
    private String TOTAL_CHARPTER_FORMAT;
    private String year_string;
    private String month_string;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newmainwork_layout);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        Intent intent = getIntent();
        wp_id = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        TOTAL_CHARPTER_FORMAT = getString(R.string.total_charpter_count);
        year_string = getString(R.string.year);
        month_string = getString(R.string.month);
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        View mActionBarView = findViewById(R.id.base_action_bar);
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.my_writework));
    }

    @Override
    protected void initUi() {
        mListView = (ListView) findViewById(R.id.listview);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View headerView = layoutInflater.inflate(R.layout.mainwork_header, mListView, false);
        tvMainworkTotalCount = (TextView) headerView.findViewById(R.id.tv_mainwork_totalcount);
        mListView.addHeaderView(headerView);
    }

    @Override
    protected void initAction() {
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int state) {
                if (state == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && mLastItemVisible) {
                    if (!loading) {
                        if (!end_flag) {
                            page++;
                            loading = true;
                            initWorkData();
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                mLastItemVisible = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1);
            }
        });
    }

    @Override
    protected void initData() {
        initYearData();
        initWorkData();
    }

    private void initYearData() {
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.WPID, wp_id));
        String url = HttpUtils.BASE_URL + SpaceApi.getNovelStats();
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject result = new JSONObject(s);
                    if (StatusCodeUtils.dealStatusCode(s, WriteWorkActivity.this)) {
                        Gson gson = new Gson();
                        JSONObject data = result.getJSONObject("data");
                        totalCount = data.getString("count");
                        tvMainworkTotalCount.setText(String.format(TOTAL_CHARPTER_FORMAT, totalCount));
                        JSONObject monthDataObj = data.getJSONObject("month_data");
                        Calendar calendar = Calendar.getInstance();
                        int year = calendar.get(Calendar.YEAR);
                        while (year > 2010) {
                            if (monthDataObj.has(String.valueOf(year))) {
                                WorkYear workYear = gson.fromJson(monthDataObj.getString(String.valueOf(year)), WorkYear.class);
                                workYearMap.put(String.valueOf(year), workYear);
                            }
                            year--;
                        }
                        year_flag = true;
                        if (work_flag) {
                            processData(tempList);
                            setAdapter();
                        }
                    } else {
                        mProgressbarHelper.onFailed();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void initWorkData() {
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair("wp_id", wp_id));
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + SpaceApi.getNovelPosts();
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject result = new JSONObject(s);
                    if (StatusCodeUtils.dealStatusCode(s, WriteWorkActivity.this)) {
                        Gson gson = new Gson();
                        tempList = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA),
                                new TypeToken<List<Novel>>() {
                                }.getType());
                        if (tempList.size() == 0)
                            end_flag = true;
                        work_flag = true;
                        if (page != 1) {
                            processData(tempList);
                            setAdapter();
                        } else {
                            if (year_flag) {
                                processData(tempList);
                                setAdapter();
                            }
                        }
                    } else {
                        mProgressbarHelper.onFailed();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void processData(List<Novel> tempList) {
        for (Novel novel : tempList) {
            if (!TextUtils.isEmpty(novel.getWork()))
                novel.getPost_tags().add(0, new TagDetail(novel.getWid(), novel.getWork(), novel.getWork()));
        }
        for (int i = 0; i < tempList.size(); i++) {
            Novel novel = tempList.get(i);
            String ctime = novel.getCtime();
            String[] ctimes = ctime.split("-");
            String year = ctimes[0];
            String month = ctimes[1];
            WorkMonth workMonth = workYearMap.get(year).getWorkMonth(month);
            String date = year + year_string + month + month_string;
            if (!existedWorkMonth.contains(date)) {
                workMonth.setDate(date);
                existedWorkMonth.add(date);
                NativeWriteWork nativeHeadWriteWork = new NativeWriteWork();
                nativeHeadWriteWork.setWorkMonth(workMonth);
                nativeHeadWriteWork.setType(0);
                nativeWriteWorkList.add(nativeHeadWriteWork);
            }
            NativeWriteWork nativeWriteWork = new NativeWriteWork();
            nativeWriteWork.setNovel(novel);
            nativeWriteWork.setType(1);
            nativeWriteWorkList.add(nativeWriteWork);
        }
    }

    private void setAdapter() {
        if (null == myNovelAdapter) {
            myNovelAdapter = new MyNovelAdapter(this, nativeWriteWorkList);
            mListView.setAdapter(myNovelAdapter);
        } else {
            myNovelAdapter.setData(nativeWriteWorkList);
            myNovelAdapter.notifyDataSetChanged();
        }
        loading = false;
        mProgressbarHelper.onSuccess();
    }
}
